
const AirtelUgxPageTag = require("./airtelUgxPageTag.js");
const Constant = require("./constant.js");
const ApiUrl = require("./baseApiUrl.js");
const BaseStringUtil = require("./baseStringUtil.js");
const RunDefine = require("./baseRunDefine.js");
const BaseKeyboardDefine = require("./baseKeyboardDefine.js");

/** pin 首个输入框坐标 */
const pinEditPoint = {
    x: 130,
    y: 860
}

/** 根据数字获取数字键盘坐标 */
const getNumberKeoyboardPoint = (num) => {
    if ("0" === num) {
        return BaseKeyboardDefine.code0;
    } else if ("1" === num) {
        return BaseKeyboardDefine.code1;

    } else if ("2" === num) {
        return BaseKeyboardDefine.code2;

    } else if ("3" === num) {
        return BaseKeyboardDefine.code3;

    } else if ("4" === num) {
        return BaseKeyboardDefine.code4;

    } else if ("5" === num) {
        return BaseKeyboardDefine.code5;

    } else if ("6" === num) {
        return BaseKeyboardDefine.code6;

    } else if ("7" === num) {
        return BaseKeyboardDefine.code7;

    } else if ("8" === num) {
        return BaseKeyboardDefine.code8;

    } else if ("9" === num) {
        return BaseKeyboardDefine.code9;

    }
    return null;
}

/** pin输入，点击键盘 */
const doInputPinCode = () => {

    sleep(1000);

    let allInput = true;
    let pinCodes = Constant.getPin();
    if (pinCodes.length >= 4) {
        sleep(500);
        let code1 = pinCodes.substring(0, 1);
        let code1Point = getNumberKeoyboardPoint(code1);
        if (code1Point) {
            click(code1Point.x, code1Point.y);
            sleep(500);
        } else {
            allInput = false;
        }

        let code2 = pinCodes.substring(1, 2);
        let code2Point = getNumberKeoyboardPoint(code2);
        if (code2Point) {
            click(code2Point.x, code2Point.y);
            sleep(500);
        } else {
            allInput = false;
        }

        let code3 = pinCodes.substring(2, 3);
        let code3Point = getNumberKeoyboardPoint(code3);
        if (code3Point) {
            click(code3Point.x, code3Point.y);
            sleep(500);
        } else {
            allInput = false;
        }

        let code4 = pinCodes.substring(3, 4);
        let code4Point = getNumberKeoyboardPoint(code4);
        if (code4Point) {
            click(code4Point.x, code4Point.y);
            sleep(1000);
        } else {
            allInput = false;
        }

        return allInput;
    }
    return false;
}

// 操作 登录
const doLogin = () => {
    let editList = className("EditText").find();
    // console.log("doLogin-判断是否为登录页-editList " +editList.length)
    console.log(Constant.UI_SDK_VERSION + "doLogin-开始操作登录");
    for (let index = 0; index < editList.length; index++) {
        let tv = editList[index];
        let curText = tv.text() || ""
        console.log(Constant.UI_SDK_VERSION + "doLogin-当前: " + index + ", 内容: " + curText)

        if (curText.indexOf(AirtelUgxPageTag.loginPageTag1) !== -1) {
            console.log(Constant.UI_SDK_VERSION + "doLogin-设置登录手机号: " + Constant.getMtn());
            tv.setText(Constant.getMtn());

            sleep(500);
            back();
            sleep(1000);
            console.log(Constant.UI_SDK_VERSION + "doLogin-点击登录");
            click(device.width * 0.5, device.height - 60); // 提交按钮
            sleep(500);

            editList.length = 0;
            editList = null;
            return true;
        }
    }

    editList.length = 0;
    editList = null;
    console.log(Constant.UI_SDK_VERSION + "doLogin-操作登录结束: 当前不是登录页")
    return false;
}

// 操作 登录-pin
const doPin = () => {
    console.log(Constant.UI_SDK_VERSION + "doPin-开始操作登录-pin");
    return doInputPinCode();
}

// 操作 打开 home 页
const doClickTabHome = () => {
    // 点击 Cash
    console.log(Constant.UI_SDK_VERSION + "doClickTabHome-开始操作打开 Home 页");
    click(device.width / 10 * 3, device.height - 60);
    sleep(1000);
    return true;
}

// 操作 打开 tab airtel money 页
const doClickTabAirtelMoney = () => {
    // 点击 Cash
    console.log(Constant.UI_SDK_VERSION + "doClickTabAirtelMoney-开始操作打开 tab airtel money 页");
    click(device.width / 8 * 3, device.height - 60);
    sleep(1000);
    return true;
}

// 操作 打开 tab more 页
const doClickTabMore = () => {
    // 点击 Cash
    console.log(Constant.UI_SDK_VERSION + "doClickTabMore-开始操作打开 tab more 页");
    click(device.width / 8 * 7, device.height - 60);
    sleep(1000);
    return true;
}

// 操作 打开 tab more airtel money services 页
const doClickTabMoreAirtelMoneyServices = () => {
    // 点击 Cash
    console.log(Constant.UI_SDK_VERSION + "doClickTabMoreAirtelMoneyServices-开始操作打开 tab more airtel money services 页");
    click(AirtelUgxPageTag.tabMorePageTag2);
    sleep(1000);
    return true;
}

// 操作 打开 tab more transaction history 页
const doClickTabMoreTransactionHistory = () => {
    // 点击 Cash
    console.log(Constant.UI_SDK_VERSION + "doClickTabMoreTransactionHistory-开始操作打开 tab more transaction history 页");
    click(AirtelUgxPageTag.tabMorePageTag5);
    sleep(1000);
    return true;
}

// 操作 打开 send money 页
const doClickSendMoney = () => {
    // 点击 Send money
    console.log(Constant.UI_SDK_VERSION + "doClickSendMoney-开始操作打开 Send money 页");
    sleep(500);
    click(AirtelUgxPageTag.tabAirtelMoneyPageTagSendMoney);
    sleep(1000);
    return true;
}

// 操作 打开 send money 页
const doClickAirtelPayment = () => {
    // 点击 Send money
    console.log(Constant.UI_SDK_VERSION + "doClickAirtelPayment-开始操作打开 Airtel Payment 页");
    sleep(500);
    click(AirtelUgxPageTag.sendMoneyPageTag2);
    sleep(1000);
    return true;
}

/** 操作 输入对方钱包号 */
const doInputTargetAccount = (targetAccount) => {
    // 输入对方钱包号
    console.log(Constant.UI_SDK_VERSION + "doInputTargetAccount-开始操作输入对方钱包号");

    let editList = className("EditText").find();

    for (let index = 0; index < editList.length; index++) {
        let tv = editList[index];
        let curText = tv.text() || ""
        console.log(Constant.UI_SDK_VERSION + "doInputTargetAccount-当前: " + index + " +内容: " + curText);

        if (curText.indexOf(AirtelUgxPageTag.sendMoneyAccountInputPageTag1) !== -1) {
            console.log(Constant.UI_SDK_VERSION + "doInputTargetAccount-设置 input account: " + targetAccount);
            tv.setText(targetAccount);

            sleep(1000);
            editList.length = 0;
            editList = null;
            return true;
        }
    }

    editList.length = 0;
    editList = null;
    console.log(Constant.UI_SDK_VERSION + "doInputTargetAccount-输入失败");
    return false;
}

/** 操作 输入转账金额 */
const doInputTargetAmount = (targetAmount) => {
    // 输入对方钱包号
    console.log(Constant.UI_SDK_VERSION + "doInputTargetAmount-开始操作输入金额");

    let editList = className("EditText").find();

    if (editList.length > 1) {
        let tv = editList[1];
        console.log(Constant.UI_SDK_VERSION + "doInputTargetAmount-设置 input amount: " + targetAmount);
        tv.setText(targetAmount);

        editList.length = 0;
        editList = null;

        let textList = className("TextView").find();
        for (let index = 0; index < textList.length; index++) {
            let proceedTv = textList[index];
            let curText = (proceedTv.text() || "").trim();
            console.log(Constant.UI_SDK_VERSION + "doInputTargetAmount-当前: " + index + " +内容: " + curText);

            if (curText.indexOf(AirtelUgxPageTag.sendMoneyAccountInputDonePageTag5) !== -1) {
                let doneBounds = proceedTv.bounds();
                click(doneBounds.centerX(), doneBounds.centerY());

                textList.length = 0;
                textList = null;
                return true;
            }
        }
        textList.length = 0;
        textList = null;

        let buttonList = className("Button").find();
        for (let index = 0; index < buttonList.length; index++) {
            let proceedBtn = buttonList[index];
            let curText = (proceedBtn.text() || "").trim();
            console.log(Constant.UI_SDK_VERSION + "doInputTargetAmount-当前: " + index + " +内容: " + curText);

            if (curText.indexOf(AirtelUgxPageTag.sendMoneyAccountInputDonePageTag5) !== -1) {
                let doneBounds = proceedBtn.bounds();
                click(doneBounds.centerX(), doneBounds.centerY());

                buttonList.length = 0;
                buttonList = null;
                return true;
            }
        }
        buttonList.length = 0;
        buttonList = null;
    }

    editList.length = 0;
    editList = null;
    console.log(Constant.UI_SDK_VERSION + "doInputTargetAmount-输入失败");
    return false;
}

// 操作 点击确认转账
const doConfirmSendMoney = () => {
    // 输入对方钱包号
    console.log(Constant.UI_SDK_VERSION + "doConfirmSendMoneyPage-开始操作确认转账");

    // click(device.width * 0.5, device.height - 60); // 提交按钮
    click(AirtelUgxPageTag.sendMoneyConfirmPageTagDone)
    sleep(500);
    return true;
}

// 操作 点击输入转账密码
const doInputSendMoneyPassword = () => {
    // 输入对方钱包号
    console.log(Constant.UI_SDK_VERSION + "doInputSendMoneyPassword-开始操作输入转账密码");
    return doInputPinCode();
}

// 操作 点击 Done 结束返回
const doClickTransferDoneAndGoBack = () => {
    // 点击 back
    console.log(Constant.UI_SDK_VERSION + "doClickTransferDoneAndGoBack-开始操作点击 Done");
    click(device.width * 0.9, 150);
    sleep(1000);
    return true;
}

// 操作 点击 Done 结束返回
const doClickTransferFailAndGoBack = () => {
    // 点击 back
    console.log(Constant.UI_SDK_VERSION + "doClickTransferFailAndGoBack-开始操作点击 Done");
    click(device.width * 0.9, 150);
    sleep(1000);
    return true;
}

// 操作 点击 Transactions
const doClickCheckBills = () => {
    // 点击 Transactions
    console.log(Constant.UI_SDK_VERSION + "doClickCheckBills-开始操作点击 Transactions");
    click(AirtelUgxPageTag.homePageTag4);
    return true;
}

// 操作 点击 确认查看流水
const doClickBillCheckProceed = () => {
    // 点击 Transactions
    console.log(Constant.UI_SDK_VERSION + "doClickBillCheckProceed-开始操作点击 ok please proceed");
    click(AirtelUgxPageTag.transactionAskPageTag4);
    return true;
}

// 操作 输入pin码-查看流水
const doInputBillCheckPin = () => {
    // 点击 Transactions
    console.log(Constant.UI_SDK_VERSION + "doInputBillCheckPin-开始操作输入pin码");
    return doInputPinCode();
}

// ==================== 流水操作-start ====================
// 上报缓存记录
const mBillIdsCached = [];

// 首屏记录
const mFirstScreenBillsCached = [];

// 上一屏记录
const mLastScreenBillsCached = [];

/**
 *  判断两个bill item是否相同
 */
const doIsSameBillItems = (billItem1, billItem2) => {
    if (!billItem1) {
        return false;
    }
    if (!billItem2) {
        return false;
    }

    // 判断是否发生变化
    let transactionIDChanged = (billItem1.transactionID !== billItem2.transactionID);
    if (transactionIDChanged) {
        return false;
    }

    // let isTypeChanged = (billItem1.type !== billItem2.type);
    // let isBalanceChanged = (billItem1.balance !== billItem2.balance);
    // let transactionID = (billItem1.transactionID !== billItem2.transactionID);
    // let isDateChanged = (billItem1.date !== billItem2.date);
    // let isStatusChanged = (billItem1.status !== billItem2.status);
    // if (isTypeChanged || isBalanceChanged || transactionID || isDateChanged || isStatusChanged) {
    //     return false;
    // }

    // 默认相同
    return true;
}

/**
* 判断两屏数据是否发生变动
* @param bill1 目标数组
* @param bill2 旧数组，拿来作比较用
*/
const doIsBillsListChanged = (bill1, bill2) => {
    // 改变状态详情
    let changedStatus = {
        isBillsChanged: false
    };
    if ((!bill1) && (bill2)) {
        changedStatus.isBillsChanged = false;
        return changedStatus;
    }
    if ((bill1) && (!bill2)) {
        changedStatus.isBillsChanged = true;
        return changedStatus;
    }
    if ((bill1.length > 0) && (bill2.length == 0)) {
        changedStatus.isBillsChanged = true;
        return changedStatus;
    }
    if ((bill1.length == 0) && (bill2.length > 0)) {
        changedStatus.isBillsChanged = false;
        return changedStatus;
    }

    // 长度 <
    if (bill1.length < bill2.length) {
        changedStatus.isBillsChanged = true;
        return changedStatus;
    }

    // 长度 =
    if (bill1.length === bill2.length) {
        changedStatus.isBillsChanged = false;
        // 循环遍历
        for (let rIndex = 0; rIndex < bill1.length; rIndex++) {
            let bill1ItemNext = bill1[rIndex];
            let bill2ItemNext = bill2[rIndex];

            let isSameBillItem = doIsSameBillItems(bill1ItemNext, bill2ItemNext);
            console.log("======= " + rIndex + " < -isSameBillItem:" + isSameBillItem);

            // 第n个发生变化
            if (!isSameBillItem) {
                changedStatus.isBillsChanged = true;
                return changedStatus;
            }
        }
        return changedStatus;
    }

    // 长度 >
    if (bill1.length > bill2.length) {
        changedStatus.isBillsChanged = true;
        return changedStatus;
    }

    changedStatus.isBillsChanged = false;
    return changedStatus;
};

/**
 *  深拷贝首页短流水记录
 *  @param arr1 目标数组
 *  @param arr2 待复制数据
 */
const doDeepCloneShortBills = (arr1, arr2) => {
    if (!arr2) {
        return;
    }

    if (!arr1) {
        arr1 = [];
        return;
    }

    // 重置
    arr1.length = 0;
    // 深拷贝
    for (let di = 0; di < arr2.length; di++) {
        let diItem = arr2[di];
        let cloneItem = {};
        cloneItem.type = diItem.type;
        cloneItem.transactionID = diItem.transactionID;
        arr1.push(cloneItem);
    }
};

// 新增流水详情缓存
const doAddBillRecord = (billItem) => {
    if (billItem) {
        let transactionID = billItem.transactionID;
        if (doIsBillRecordExist(transactionID)) {
            return false;
        } else {
            mBillIdsCached.push(billItem);
            return true;
        }
    }
    return false;
};

// 查询交易流水是否存在缓存
const doIsBillRecordExist = (transactionID) => {
    if (!transactionID) {
        return false;
    }

    for (let i = 0; i < mBillIdsCached.length; i++) {
        let item = mBillIdsCached[i];
        if (item.transactionID.startsWith(transactionID)) {
            console.log(Constant.UI_SDK_VERSION + "doIsBillRecordExist-交易id已存在, 不作处理-" + transactionID);
            return true;
        }
    }
    console.log(Constant.UI_SDK_VERSION + "doIsBillRecordExist-交易id不存在, 增加到缓存-" + transactionID);

    return false;
};

// 查询当前屏的数据
const doGetBillsForCurrentScreen = () => {
    // 数据列表
    let dataList = [];
    // 是否到底部了
    let didBottom = false;

    // 读取当前列表
    let textList = className("TextView").find();
    let startIndex = 0;
    while (startIndex < textList.length) {
        let curTv = textList[startIndex];
        let curText = curTv.text() || "";

        // 判断是否为有效的记录
        let isRecordTagTransactionID = (curText.indexOf(AirtelUgxPageTag.transactionListItemTagTransactionID) !== -1);
        console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-当前: " + startIndex + ", 内容: " + curText + ", isRecordTagTransactionID: " + isRecordTagTransactionID + ", didBottom" + didBottom);

        if (isRecordTagTransactionID) {

            // 判断 transaction id 是否在可视范围内
            let canClick = (curTv.bounds().bottom <= device.height);
            console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-status: " + findText + ", top: " + curTv.bounds().top + ", bottom: " + curTv.bounds().bottom + ", canClick: " + canClick);

            if (!canClick) {
                // 不是有效的行数据, 需要往下滑
                console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-已经读完当前屏幕的有效数据, 跳出循环,  最后一行的Y坐标: " + curTv.bounds().bottom);
                startIndex = textList.length;
                continue;
            }

            // 这是行开头, 再判断是否为完整的行记录
            let typeIndex = (startIndex - 2);
            let typeTv = textList[typeIndex];
            let typeValue = typeTv.text() || "";

            let transactionIDValue = null;
            let transactionIDValueIndex = -1;
            let transactionIDValueBottom = 0;

            // 找到 transaction id
            if (BaseStringUtil.isTransactionIDFormatAirtelUgx(curText)) {
                transactionIDValue = curText;

                // 最后一行的Y坐标
                transactionIDValueIndex = startIndex;
                transactionIDValueBottom = curTv.bounds().bottom;

            } else {
                transactionIDValueIndex = (startIndex + 1);
                if (textList.length > transactionIDValueIndex) {
                    let transactionIDTv = textList[transactionIDValueIndex];
                    transactionIDValue = transactionIDTv.text() || "";

                    // 最后一行的Y坐标
                    transactionIDValueIndex = transactionIDValueIndex;
                    transactionIDValueBottom = transactionIDTv.bounds().bottom;
                }
            }

            // 如果全部都有效，才缓存
            if (typeValue && transactionIDValue) {
                // 添加缓存
                let rowData = {};
                rowData.type = typeValue;
                rowData.transactionID = transactionIDValue;
                rowData.top = curTv.bounds().top;
                rowData.bottom = statusValueBottom;
                rowData.centerX = curTv.bounds().centerX();
                rowData.centerY = curTv.bounds().centerY();
                dataList.push(rowData);

                // 添加缓存
                doAddBillRecord(rowData);

                console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-读完-准备下一个游标=====");
                // 更新起始位置
                startIndex = (statusValueIndex + 1);
                // sleep(1 * 1000);
                continue;
            }
        }
        startIndex += 1;
    }

    textList.length = 0;
    textList = null;

    // 找出最后一个有效行的底部坐标
    let lastValidRowY = 0;
    if (dataList.length > 0) {
        let lastItem = dataList[dataList.length - 1];
        lastValidRowY = lastItem.bottom;
    }

    // 打印
    console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-共有效数据: " + dataList.length);
    console.log(dataList);

    // 判断是否到底
    if (mLastScreenBillsCached) {
        if ((dataList.length === 0) && (mLastScreenBillsCached.length === 0)) {
            didBottom = true;

        } else if (dataList.length === mLastScreenBillsCached.length) {
            didBottom = (!doIsBillsListChanged(dataList, lastBillList));
        }
    }

    // 缓存当前屏数据
    doDeepCloneShortBills(mLastScreenBillsCached, dataList);

    return { dataList: dataList, didBottom: didBottom, lastValidRowY: lastValidRowY };
};

// 处理每个版页的数据需求
const doScanBillsForEachScreen = () => {

    // 控制缓存不超过20条
    let needDelCount = (mBillIdsCached.length - 20);
    if (needDelCount > 0) {
        mBillIdsCached.splice(0, needDelCount);
    }

    // 最多遍历5次, 测试来看足够了
    let xPullStart = (device.width * 0.8);
    let yPullStart = 200;
    let yPullEnd = (device.height - 60);

    // 滑动到顶部
    swipe(xPullStart, yPullStart, xPullStart, yPullEnd, 1000);
    sleep(2 * 1000);

    for (let pageSize = 0; pageSize < 50; pageSize++) {
        console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-pageSize:" + pageSize + "==========");

        // 先查出当前屏的有效数据
        let curScreenBillInfo = doGetBillsForCurrentScreen(mLastScreenBillsCached);
        let curScreenBillList = curScreenBillInfo.dataList;
        let didBottom = curScreenBillInfo.didBottom;

        // 判断第1屏数据有没有变动，没有变动，就不需要查流水了
        if (0 === pageSize) {
            let isFillBillsChanged = doIsBillsListChanged(curScreenBillList, mFirstScreenBillsCached);
            if (!isFillBillsChanged.isBillsChanged) {
                console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-流水数据没有发生变化，抓取结束===");
                mLastScreenBillsCached.length = 0;
                return;
            }

            // 缓存首屏数据
            doDeepCloneShortBills(mFirstScreenBillsCached, curScreenBillList);
        }

        // 如果到底了，直接返回
        if (didBottom) {
            console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-所有流水数据抓取结束===");
            // 上传数据
            // ...
            console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-开始上报数据===");
            sleep(1000);
            back();
            sleep(1000);
            return true;
        }

        // 拿到最后一个记录，取bottom为滑动起点，往上滑一屏，yEnd = 200
        if (curScreenBillList.length > 0) {
            let item = curScreenBillList[curScreenBillList.length - 1];
            console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-yStart: " + item.bottom + ", yEnd: " + yPullStart);
            swipe(xPullStart, item.bottom, xPullStart, yPullStart, 2000);
            sleep(3000);
        }
    }

    // 如果没有数据，直接返回
    console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-流水流程结束===");
    sleep(1000);
    back();
    sleep(1000);
    return true;
};

// ==================== 流水操作-end ====================

module.exports = {
    doLogin: doLogin,
    doPin: doPin,
    doClickTabHome: doClickTabHome,
    doClickTabAirtelMoney: doClickTabAirtelMoney,
    doClickTabMore: doClickTabMore,
    doClickTabMoreAirtelMoneyServices: doClickTabMoreAirtelMoneyServices,
    doClickTabMoreTransactionHistory: doClickTabMoreTransactionHistory,
    doClickSendMoney: doClickSendMoney,
    doClickAirtelPayment: doClickAirtelPayment,
    doInputTargetAccount: doInputTargetAccount,
    doInputTargetAmount: doInputTargetAmount,
    doConfirmSendMoney: doConfirmSendMoney,
    doInputSendMoneyPassword: doInputSendMoneyPassword,

    doClickTransferFailAndGoBack: doClickTransferFailAndGoBack,
    doClickTransferDoneAndGoBack: doClickTransferDoneAndGoBack,

    doClickBillCheckProceed: doClickBillCheckProceed,
    doInputBillCheckPin: doInputBillCheckPin,

    doClickCheckBills: doClickCheckBills,

    doGetBillsForCurrentScreen: doGetBillsForCurrentScreen,
    doScanBillsForEachScreen: doScanBillsForEachScreen
};